from django import forms
from .models import UserProfile
import json

class UserProfileForm(forms.ModelForm):
    # 使用CharField代替JSONField以便于用户输入
    social_media_text = forms.CharField(
        widget=forms.Textarea(attrs={'rows': 3, 'placeholder': '每行一个社交媒体链接，格式：平台名:链接'}),
        label='社交媒体链接',
        required=False,
        help_text='例如：微博:https://weibo.com/username'
    )
    
    class Meta:
        model = UserProfile
        fields = ['avatar', 'bio', 'is_creator']
        widgets = {
            'bio': forms.Textarea(attrs={'rows': 4}),
        }
        labels = {
            'avatar': '头像',
            'bio': '个人简介',
            'is_creator': '申请成为创作者',
        }
    
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        if instance:
            # 将JSONField转换为文本形式
            social_media = instance.social_media or {}
            social_media_text = "\n".join([f"{k}:{v}" for k, v in social_media.items()])
            if 'initial' not in kwargs:
                kwargs['initial'] = {}
            kwargs['initial']['social_media_text'] = social_media_text
        super().__init__(*args, **kwargs)
    
    def save(self, commit=True):
        instance = super().save(commit=False)
        
        # 将文本形式的社交媒体链接转换为JSON
        social_media_text = self.cleaned_data.get('social_media_text', '')
        social_media = {}
        
        if social_media_text:
            for line in social_media_text.strip().split('\n'):
                if ':' in line:
                    platform, url = line.split(':', 1)
                    social_media[platform.strip()] = url.strip()
        
        instance.social_media = social_media
        
        if commit:
            instance.save()
        
        return instance 